<template>
  <div class="video-view">
    <div class="video-header">
      <h2 class="video-title">视频播放</h2>
      <el-button plain @click="handleReturn">
        <el-icon><Back /></el-icon> 返回
      </el-button>
    </div>
    
    <div class="video-container">
      <video 
        v-if="!videoError"
        ref="videoRef"
        :src="videoUrl" 
        class="main-video" 
        controls 
        autoplay
        playsinline
        webkit-playsinline
        x5-video-player-type="h5"
        x5-video-orientation="landscape"
        x-webkit-airplay="allow"
        crossorigin="anonymous"
        @error="handleVideoError"
      >
        您的浏览器不支持视频播放
      </video>
      
      <div v-if="videoError" class="video-error">
        <el-icon class="error-icon"><VideoPlay /></el-icon>
        <p class="error-text">视频加载失败，请检查视频地址或网络连接</p>
        <div class="error-actions">
          <el-button type="primary" @click="tryReloadVideo">重试</el-button>
          <el-button type="success" @click="downloadVideo">下载视频</el-button>
          <el-button @click="window.open(videoUrl, '_blank')">新窗口打开</el-button>
        </div>
      </div>
    </div>
    
    <div class="video-controls" v-if="!videoError">
      <el-button type="primary" @click="toggleFullScreen">
        <el-icon><FullScreen /></el-icon> 全屏播放
      </el-button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { FullScreen, Back, VideoPlay } from '@element-plus/icons-vue'
import { registerVideo, unregisterVideo } from '@/utils/videoManager'

export default {
  name: 'VideoView',
  components: {
    FullScreen,
    Back,
    VideoPlay
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const videoUrl = ref('');
    const videoRef = ref(null);
    const videoError = ref(false);
    
    // 添加返回路径和好友ID的响应式变量
    const returnPath = ref('/home');
    const friendId = ref('');
    
    const loadVideo = () => {
      const url = route.query.url;
      
      if (url) {
        try {
          // 尝试多种解码方式
          let decodedUrl = url;
          
          // 检查是否已经是完整URL
          if (!url.startsWith('http')) {
            try {
              decodedUrl = decodeURIComponent(url);
            } catch (e) {
              console.warn('第一次解码失败，尝试替代方法');
              // 某些情况下可能需要多次解码
              try {
                decodedUrl = decodeURIComponent(decodeURIComponent(url));
              } catch (e2) {
                console.warn('第二次解码失败，使用原始URL');
                decodedUrl = url;
              }
            }
          }
          
          console.log('解码后的视频URL:', decodedUrl);
          videoUrl.value = decodedUrl;
          videoError.value = false;
          
          // 强制设置视频方向为横向播放
          setTimeout(() => {
            if (videoRef.value) {
              videoRef.value.setAttribute('style', 'transform: none !important; object-fit: contain !important;');
              videoRef.value.setAttribute('crossorigin', 'anonymous');
              // 注册视频到视频管理器
              registerVideo(videoRef.value);
            }
          }, 100);
        } catch (err) {
          console.error('解码视频URL失败:', err);
          videoError.value = true;
          ElMessage.error('视频URL格式错误');
        }
      } else {
        videoError.value = true;
        ElMessage.error('未提供视频地址');
        // 3秒后返回上一页
        setTimeout(() => {
          handleReturn();
        }, 3000);
      }
    };
    
    const tryReloadVideo = () => {
      videoError.value = false;
      loadVideo();
    };
    
    onMounted(() => {
      // 从路由查询参数获取视频URL和相关信息
      const from = route.query.from || '/home'; // 获取来源页面路径，默认为home
      const fId = route.query.friendId || '';
      
      // 保存来源路径和好友ID到组件属性
      returnPath.value = from;
      friendId.value = fId;
      
      // 加载视频
      loadVideo();
    });
    
    // 组件销毁前清理
    onBeforeUnmount(() => {
      if (videoRef.value) {
        // 从视频管理器中移除
        unregisterVideo(videoRef.value);
      }
    });
    
    const handleVideoError = (e) => {
      console.error('视频加载失败:', e);
      
      // 视频加载失败时，直接返回聊天界面
      ElMessage.error('视频加载失败，正在返回聊天界面');
      setTimeout(() => {
        handleReturn();
      }, 1500);
    };

    // 尝试使用img标签显示视频第一帧（对某些格式有效）
    const tryImgFallback = () => {
      if (!videoUrl.value) return;
      
      const img = new Image();
      img.onload = () => {
        console.log('成功加载视频帧作为图片');
        // 这里可以显示一个静态图片代替视频
      };
      img.onerror = () => {
        console.error('无法加载视频帧作为图片');
      };
      img.src = videoUrl.value;
    };
    
    // 添加直接下载视频的方法
    const downloadVideo = () => {
      if (!videoUrl.value) {
        ElMessage.warning('没有可下载的视频');
        return;
      }
      
      try {
        const a = document.createElement('a');
        a.href = videoUrl.value;
        // 提取文件名
        const urlParts = videoUrl.value.split('/');
        const fileName = urlParts[urlParts.length - 1].split('?')[0] || 'video.mp4';
        a.download = fileName;
        a.target = '_blank';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (err) {
        console.error('下载视频失败:', err);
        ElMessage.error('下载失败，请直接在新标签页中打开视频');
        // 备用方案：在新窗口打开
        window.open(videoUrl.value, '_blank');
      }
    };
    
    const toggleFullScreen = () => {
      if (!videoRef.value) return;
      
      try {
        if (document.fullscreenElement) {
          document.exitFullscreen();
        } else {
          videoRef.value.requestFullscreen();
        }
      } catch (err) {
        console.error('全屏切换失败:', err);
        ElMessage.warning('全屏切换失败，请使用视频自带的全屏按钮');
      }
    };
    
    // 新增处理返回的方法
    const handleReturn = () => {
      // 停止视频播放
      if (videoRef.value) {
        videoRef.value.pause();
        videoRef.value.src = ''; // 清空视频源
        unregisterVideo(videoRef.value);
      }
      
      // 如果有好友ID，构建带有选中好友的返回URL
      if (friendId.value) {
        router.push({
          path: returnPath.value,
          query: { selectFriend: friendId.value }
        });
      } else {
        // 否则直接返回
        router.push(returnPath.value);
      }
    };
    
    return {
      videoUrl,
      videoRef,
      videoError,
      handleVideoError,
      toggleFullScreen,
      handleReturn,
      returnPath,
      friendId,
      tryReloadVideo,
      downloadVideo,
      tryImgFallback
    };
  }
}
</script>

<style scoped>
.video-view {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.video-header {
  width: 90%;
  max-width: 1200px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.video-title {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.video-container {
  width: 90%;
  max-width: 1200px;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-video {
  width: 100%;
  max-height: 80vh;
  object-fit: contain !important;
  transform: none !important; /* 防止自动旋转 */
  background-color: #000;
  -webkit-transform: none !important;
  -moz-transform: none !important;
  -ms-transform: none !important;
  -o-transform: none !important;
}

.video-controls {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.video-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  color: #909399;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #C0C4CC;
}

.error-text {
  font-size: 16px;
  margin-bottom: 16px;
}

.error-actions {
  display: flex;
  gap: 10px;
}
</style> 